/**
 * 
 */
package com.qianhai.manage.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.qianhai.manage.service.IImageService;
import com.qianhai.manage.service.INewsService;
import com.qianhai.manage.service.INewsTypeService;
import com.qianhai.manage.util.OperationUtil;
import com.qianhai.manage.util.StringUtil;
import com.qianhai.manage.util.TransformationUtil;
import com.qianhai.manage.vo.ImageInfo;
import com.qianhai.manage.vo.NewsInfo;
import com.qianhai.manage.vo.NewsTypeInfo;

/**
 * @author Administrator
 *
 */
@Controller
@RequestMapping("news")
public class NewsController extends BaseController {
	
	private Logger logger = LoggerFactory.getLogger(NewsController.class);
	
	@Resource
	private IImageService imageService;
	@Resource
	private INewsTypeService newsTypeService;
	@Resource
	private INewsService newsService;
	
	private final static String PATH = "/root/show-web/lib/webapp/static/wx_static/site_media/html";
//	private final static String PATH = "C:\\Program Files (x86)\\Apache Software Foundation\\Tomcat 7.0\\webapps\\qhmanage\\upload/html";
	
	@RequestMapping("newstype")
	public String toNewsType() {
		return "news/newstype";
	}
	
	@RequestMapping("newsinit")
	public String toNews() {
		return "news/news";
	}
	
	@RequestMapping("banner")
	public String  toBanner(ModelMap map) {
		map.put("leveltype", 1);
		return "news/banner";
	}
	
	@RequestMapping("banner4news")
	public String  toBanner4New(ModelMap map) {
		map.put("leveltype", 2);
		return "news/banner";
	}
	
	@RequestMapping("addnewstype")
	public String addNewsType(ModelMap map) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("level", 1);
		List<NewsTypeInfo> ml = this.newsTypeService.selectNewsTypeInfos(param, 0, 0);
		map.put("ml", ml);
		return "news/editnewstype";
	}
	
	@RequestMapping("editnewstype")
	public String editNewsType(String cid, ModelMap map) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("cid", cid);
		List<NewsTypeInfo> list = this.newsTypeService.selectNewsTypeInfos(param, 0, 0);
		if(list == null || list.isEmpty()) {
			map.put("msg", "参数有误！");
			return "error";
		}
		NewsTypeInfo vo = list.get(0);
		map.put("vo", vo);
		return "news/editnewstype";
	}
	
	@RequestMapping("addnews")
	public String toAddNews(ModelMap map) {
		String pid = UUID.randomUUID().toString().replace("-", "");
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("level", 1);
		List<NewsTypeInfo> ml = this.newsTypeService.selectNewsTypeInfos(param, 0, 0);
		map.put("ml", ml);
		map.put("pid", pid);
		return "news/editnews";
	}
	
	@RequestMapping("editnews")
	public String toEditNews(String cid, ModelMap map) {
		map.put("pid", cid);
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("cid", cid);
		List<NewsInfo> list = this.newsService.selectNewsInfos(param, 0, 0);
		if(list == null || list.isEmpty()) {
			map.put("msg", "参数有误！");
			return "error";
		}
		this.setNewsContent(list);
		NewsInfo vo = list.get(0);
		Map<String, Object> sparam = new HashMap<String, Object>();
		sparam.put("level", 1);
		List<NewsTypeInfo> ml = this.newsTypeService.selectNewsTypeInfos(sparam, 0, 0);
		map.put("ml", ml);
		map.put("vo", vo);
		return "news/editnews";
	}
	
	@RequestMapping("shownews")
	public String toShowNews(String cid, ModelMap map) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("cid", cid);
		List<NewsInfo> list = this.newsService.selectNewsInfos(param, 0, 0);
		if(list == null || list.isEmpty()) {
			map.put("msg", "参数有误！");
			return "error";
		}
		this.setNewsContent(list);
		NewsInfo vo = list.get(0);
		map.put("vo", vo);
		return "news/shownews";
	}
	
	@RequestMapping("editbanner")
	public String toEditBanner(String cid, String type, ModelMap map) {
		map.put("cid", cid);
		map.put("type", type);
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("cid", cid);
		List<NewsInfo> list = this.newsService.selectNewsInfos(param, 0, 0);
		if(list == null || list.isEmpty()) {
			map.put("msg", "参数有误！");
			return "error";
		}
		this.setNewsContent(list);
		NewsInfo vo = list.get(0);
		map.put("vo", vo);
		return "news/editbanner";
	}
	
	@ResponseBody
	@RequestMapping("querynewstype")
	public Map<String, Object> querynewstype(HttpServletRequest request, NewsTypeInfo vo) {
		Map<String, Object> result = new HashMap<String, Object>();
		int page = this.getPage(request);
		int rows = this.getRows(request);
		Map<String, Object> param = TransformationUtil.Object2HashMap(vo);
		param.put("value", vo.getValue());
		param.put("level", vo.getLevel());
		param.put("sort", "value desc");
		List<NewsTypeInfo> list = this.newsTypeService.selectNewsTypeInfos(param, page, rows);
		long count = this.newsTypeService.countNewsTypeInfos(param);
		result.put("rows", list);
		result.put("total", count);
		return result;
	}
	
	@ResponseBody
	@RequestMapping("querynewstypebyl")
	public Map<String, Object> querynewstype(String value) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<NewsTypeInfo> list = this.newsTypeService.selectNewsTypeInfosByLevel(value);
		result.put("list", list);
		result.put("result", 1);
		return result;
	}
	
	@ResponseBody
	@RequestMapping("savenewstype")
	public Map<String, Object> savenewstype(HttpServletRequest request, NewsTypeInfo vo) {
		Map<String, Object> result = new HashMap<>();
		Object _username = request.getSession().getAttribute("username");
		if(_username == null) {
			_username = "";
		}
		String username = StringUtil.addDefault(_username.toString(), "Admin");
		if(StringUtil.isEmpty(vo.getCid())) {
			String level = "1";
			if(!StringUtil.isEmpty(vo.getPid())) {
				level = "2";
			}
			vo.setLevel(level);
			vo.setCreator(username);
			this.newsTypeService.saveNewsTypeInfo(vo);
			result.put("result", 1);
		} else {
			vo.setModifiedPerson(username);
			this.newsTypeService.updateNewsTypeInfo(vo);
			result.put("result", 2);
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping("querynews")
	public Map<String, Object> querynews(HttpServletRequest request, NewsInfo vo) {
		Map<String, Object> result = new HashMap<String, Object>();
		int page = this.getPage(request);
		int rows = this.getRows(request);
		Map<String, Object> param = TransformationUtil.Object2HashMap(vo);
		param.put("type", vo.getType());
		param.put("levelt", vo.getLevelt());
		param.put("sort", "create_time desc");
		List<NewsInfo> list =  this.newsService.selectNewsInfos(param, page, rows);
		this.setNewsContent(list);
		long count = this.newsService.countNewsInfos(param);
		result.put("rows", list);
		result.put("total", count);
		return result;
	}
	
	private void setNewsContent(List<NewsInfo> list) {
		if(list != null && !list.isEmpty()) {
			for(NewsInfo vo : list) {
				String content = vo.getContent();
				StringBuffer sb = new StringBuffer();
				if(content.startsWith(PATH)) {
					BufferedReader reader = null;
					try {
						File html = new File(content);
						FileReader fr = new FileReader(html);
						reader = new BufferedReader(fr);
						String tempString = null;
						while((tempString = reader.readLine()) != null) {
							sb.append(tempString);
						}
						reader.close();
						String _content = sb.toString();
						_content = _content.replace("\'", "\\\'");
						vo.setContent(_content);
					} catch(Exception e) {
						e.printStackTrace();
					} finally {
						if(reader != null) {
							try {
								reader.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}
				
			}
		}
	}
	
	@ResponseBody
	@RequestMapping("savenews")
	public Map<String, Object> savenews(HttpServletRequest request, NewsInfo vo) {
		Map<String, Object> result = new HashMap<>();
		Object _username = request.getSession().getAttribute("username");
		if(_username == null) {
			_username = "";
		}
		String username = StringUtil.addDefault(_username.toString(), "Admin");
		String content = vo.getContent();
		if(StringUtil.isEmpty(vo.getCid())) {
			vo.setCreator(username);
			String cid = request.getParameter("pid");
			vo.setCid(cid);
			String filePath = PATH + "/" + cid + ".html";
			vo.setContent(filePath);
			this.newsService.saveNewsInfo(vo);
			result.put("result", 1);
		} else {
			vo.setModifiedPerson(username);
			vo.setContent(null);
			this.newsService.updateNewsInfo(vo);
			result.put("result", 2);
		}
		try {
			this.saveHtml(vo.getCid(), content);
		} catch (IOException e) {
			result.put("result", 3);
		}
		return result;
	}
	
	private void saveHtml(String cid, String content) throws IOException {
		File dirPath = new File(PATH);
		if(!dirPath.exists()) {
			dirPath.mkdirs();
		}
		String filePath = PATH + "/" + cid + ".html";
		File html = new File(filePath);
		if(!html.exists()) {
			html.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(html);
		fos.write(content.getBytes());
		fos.flush();
		fos.close();
	}
	
	@ResponseBody
	@RequestMapping("savebanner")
	public Map<String, Object> savebanner(HttpServletRequest request, MultipartFile file) {
		Map<String, Object> result = new HashMap<String, Object>();
		if(file != null && !file.isEmpty()) {
			try {
				String cid = request.getParameter("cid");
				if(!StringUtil.isEmpty(cid)) {
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("cid", cid);
					List<NewsInfo> list = this.newsService.selectNewsInfos(param, 0, 0);
					if(list == null || list.isEmpty()) {
						return result;
					}
					NewsInfo vo = list.get(0);
					String marks = request.getParameter("marks");
					String levelt = vo.getLevelt();
					Integer type = Integer.parseInt(levelt);
					if(type > 2) {
						result.put("result", "参数有误！");
						return result;
					}
					DateFormat df = new SimpleDateFormat("yyyyMMdd");
					byte[] bytes = file.getBytes();
	//				String uploadDir = request.getSession().getServletContext().getRealPath("/upload");
					String uploadDir = "/root/show-web/lib/webapp/static/wx_static/site_media/pics/";
					uploadDir += (type == 1 ? "banner" : "news/" + df.format(new Date()));
					File dirPath = new File(uploadDir);
					if(!dirPath.exists()) {
						dirPath.mkdirs();
					}
					String tname = file.getOriginalFilename();
					String fileName = cid + "." + StringUtil.getSuffix(tname);
					File uploadedFile = new File(uploadDir + "/" + fileName);
					FileCopyUtils.copy(bytes, uploadedFile);
					
					String path = uploadedFile.getPath();
					
					NewsInfo news = new NewsInfo();
					news.setCid(cid);
					news.setMarks(marks);
					news.setPath(path);
					String key = cid + "[&%&]" + "qhym";
					String url = "/public/banner/shownews.do?key={XX}" + OperationUtil.encode(key) + "{XX}";
					news.setUrl(url);
					this.newsService.updateNewsInfo(news);
					result.put("result", 1);
				} else {
					result.put("result", "参数有误！");
				}
			} catch(Exception e) {
				result.put("result", "系统出错！");
				logger.error("", e);
			}
		} else {
			result.put("result", "必须要上传主图片！");
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping("deletenewstype")
	public Map<String, Object> deletenewstype(HttpServletRequest request, String cids) {
		Map<String, Object> result = new HashMap<String, Object>();
		if(StringUtil.isEmpty(cids)) {
			return result;
		}
		String[] _cids = cids.split(",");
		List<String> cidl = Arrays.asList(_cids);
		this.newsTypeService.deleteNewsTypeInfos(cidl);
		result.put("result", 1);
		return result;
	}
	
	@ResponseBody
	@RequestMapping("deletenews")
	public Map<String, Object> deletenews(HttpServletRequest request, String cids) {
		Map<String, Object> result = new HashMap<String, Object>();
		if(StringUtil.isEmpty(cids)) {
			return result;
		}
		String[] _cids = cids.split(",");
		List<String> cidl = Arrays.asList(_cids);
		this.deleteNews(request, cidl);
		result.put("result", 1);
		return result;
	}
	
	@ResponseBody
	@RequestMapping("uploadImage")
	public Map<String, Object> uploadImage(HttpServletRequest request, 
			@RequestParam(value="file", required=false) MultipartFile file) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String pid = request.getParameter("pid");
			byte[] bytes = file.getBytes();
			String uploadDir = request.getSession().getServletContext().getRealPath("/upload");
			Object _username = request.getSession().getAttribute("username");
			if(_username == null) {
				_username = "";
			}
			String username = StringUtil.addDefault(_username.toString(), "Admin");
			String sep = System.getProperty("file.separator");
			uploadDir += sep + username;
			File dirPath = new File(uploadDir);
			if(!dirPath.exists()) {
				dirPath.mkdirs();
			}
			String tname = file.getOriginalFilename();
			String fileName = UUID.randomUUID().toString() + "." + StringUtil.getSuffix(tname);
			File uploadedFile = new File(uploadDir + sep + fileName);
			FileCopyUtils.copy(bytes, uploadedFile);
			
			ImageInfo image = new ImageInfo();
			image.setName(uploadDir + "/" + fileName);
			image.setTname(tname);
			image.setSuffix(StringUtil.getSuffix(tname));
			image.setPid(pid);
			image.setCreator(username);
			this.imageService.saveImageInfo(image);
			String url = "/upload" + "/" + username + "/" + fileName;
			result.put("url", url);
		} catch(Exception e) {
			result.put("url", "");
			logger.error("", e);
		}
		return result;
	}
	
	private void deleteNews(HttpServletRequest request, List<String> cids) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("cids", cids);
		List<NewsInfo> list = this.newsService.selectNewsInfos(param, 0, 0);
		if(list != null && !list.isEmpty()) {
			for(NewsInfo news : list) {
				//删除图片
				List<ImageInfo> images = this.imageService.selectImageInfos(news.getCid());
				for(ImageInfo image : images) {
					String filepath = image.getName();
					File file = new File(filepath);
					if(file.exists()) {
						file.delete();
					}
					this.imageService.deleteImageInfos(news.getCid());
				}
				
				String root_path = news.getPath();
				if(!StringUtil.isEmpty(root_path)) {
					File file = new File(root_path);
					if(file.exists()) {
						file.delete();
					}
				}
				
				String content = news.getContent();
				if(!StringUtil.isEmpty(content)) {
					File file = new File(content);
					if(file.exists()) {
						file.delete();
					}
				}
			}
			this.newsService.deleteNewsInfos(cids);
		}
	}

}
